package com.shao.intelligentsnake;

/**
 * 最简单策略，无视一切走x然后走y
 *
 * @author shaohuailin
 * @date 2024/4/20
 */
public class SimpleActionStrategy implements ActionStrategy {

    // 起点位置
    private int startPosition;
    // 终点位置
    private int endPosition;
    // 探测器
    private Probe probe;

    public SimpleActionStrategy(int startPosition, int endPosition, Probe probe) {
        this.startPosition = startPosition;
        this.endPosition = endPosition;
        this.probe = probe;
    }


    @Override
    public int[] apply() {
        int[] empty = new int[0];
        int currentPosition = startPosition;
        int[] positions = positions();
        for (int nextPosition : positions) {
            // 探测currentPosition位置是否可达nextPosition位置
            int[] alternate = this.probe.probe(currentPosition);
            boolean contains = isContains(alternate, nextPosition);
            if (!contains) {
                return empty;
            }
            currentPosition = nextPosition;
        }
        return positions;
    }

    private int[] positions() {
        // 头部坐标
        int xSnake = startPosition >> 8 & 0xFF;
        int ySnake = startPosition & 0xFF;
        // 食物坐标
        int xFood = endPosition >> 8 & 0xFF;
        int yFood = endPosition & 0xFF;
        // 存储数据
        int[] array = new int[1024];
        int arrayId = 0;
        // 优先走x
        int xOffset = xSnake - xFood;
        if (xOffset != 0) {
            for (int i = 0; i < Math.abs(xOffset); i++) {
                array[arrayId++] = (xOffset > 0 ? --xSnake : ++xSnake) << 8 | ySnake;
            }
        }
        // 然后走y
        int yOffset = ySnake - yFood;
        if (yOffset != 0) {
            for (int i = 0; i < Math.abs(yOffset); i++) {
                array[arrayId++] = xSnake << 8 | (yOffset > 0 ? --ySnake : ++ySnake);
            }
        }
        int[] res = new int[arrayId];
        if (res.length > 0) {
            System.arraycopy(array, 0, res, 0, arrayId);
        }
        return res;
    }

    private boolean isContains(int[] arr, int val) {
        for (int i : arr) {
            if (i == val) {
                return true;
            }
        }
        return false;
    }
}
